String Functions and Manipulation in C
String Functions are operations provided by the
1. strlen()
The strlen() function in C is used to find the length of a null-terminated string. It is part of the
Example of strlen() function:
#include <string.h>
int main() {
char myString[] = "Hello, World!";
// Using strlen to find the length of the string
size_t length = strlen(myString);
printf("Length of the string: %zu\n", length);
return 0;
}
Keep in mind that the length does not include the null terminator '\0', and it represents the number of characters in the string before the null terminator.
2. strcpy()
The strcpy() function in C is used to copy the contents of one string to another. It is part of the
Example of strcpy() function:
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20]; // Make sure it's large enough to hold the source string
// Using strcpy to copy the contents of the source string to the destination string
strcpy(destination, source);
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
return 0;
}
Remember, if the destination space isn't big enough for both the source string and the null terminator, it might cause a buffer overflow, leading to unpredictable issues.
3. strcat()
The strcat() function in C is used to concatenate (append) the content of one string to the end of another string. It is part of the
Example of strlcat() function:
#include <string.h>
int main() {
char destination[20] = "Hello, ";
char source[] = "World!";
// Using strcat to concatenate the content of the source string to the destination string
strcat(destination, source);
printf("Concatenated string: %s\n", destination);
return 0;
}
In this example, the strcat() function is used to concatenate the content of the source string to the end of the destination string
4. strncmp()
The strncmp() function in C is used to compare the first n characters of two strings. It is part of the
Example of strncmp() function:
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "apricot";
// Using strncmp to compare the first 3 characters of str1 and str2
int result = strncmp(str1, str2,3);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is equal to str2\n");
}
return 0;
}
In this example, the strncmp() function is used to compare the first 3 characters of the strings str1 and str2. The result is then checked, and a message is printed based on the comparison.